<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket实时听单测试</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .log-container {
            height: 400px;
            overflow-y: auto;
            background-color: #f8f9fa;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: monospace;
        }
        .log-entry {
            margin-bottom: 5px;
            padding: 2px 5px;
            border-radius: 3px;
        }
        .log-info { background-color: #d1ecf1; }
        .log-success { background-color: #d4edda; }
        .log-warning { background-color: #fff3cd; }
        .log-error { background-color: #f8d7da; }
        
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .status-connected { background-color: #28a745; }
        .status-disconnected { background-color: #dc3545; }
        .status-connecting { background-color: #ffc107; }
    </style>
</head>
<body>
    <div class="container mt-4">
        <h1 class="text-center mb-4">WebSocket实时听单测试</h1>
        
        <!-- 连接控制 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>连接控制</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="userId" class="form-label">用户ID</label>
                            <input type="text" class="form-control" id="userId" value="test_user_001" placeholder="输入用户ID">
                        </div>
                        <div class="mb-3">
                            <label for="serverUrl" class="form-label">服务器地址</label>
                            <input type="text" class="form-control" id="serverUrl" value="ws://localhost:8080/ws" placeholder="WebSocket服务器地址">
                        </div>
                        <div class="d-grid gap-2">
                            <button class="btn btn-success" onclick="connect()" id="connectBtn">连接</button>
                            <button class="btn btn-danger" onclick="disconnect()" id="disconnectBtn" disabled>断开</button>
                            <button class="btn btn-info" onclick="ping()" id="pingBtn" disabled>发送Ping</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>连接状态</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex align-items-center mb-2">
                            <span class="status-indicator status-disconnected" id="statusIndicator"></span>
                            <span id="connectionStatus">未连接</span>
                        </div>
                        <div class="mb-2">
                            <strong>连接时间:</strong> <span id="connectionTime">-</span>
                        </div>
                        <div class="mb-2">
                            <strong>消息计数:</strong> <span id="messageCount">0</span>
                        </div>
                        <div>
                            <strong>最后消息:</strong> <span id="lastMessage">-</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 消息发送 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5>消息发送</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <label for="messageType" class="form-label">消息类型</label>
                                <select class="form-select" id="messageType">
                                    <option value="ping">Ping</option>
                                    <option value="subscribe_orders">订阅订单</option>
                                    <option value="unsubscribe_orders">取消订阅订单</option>
                                    <option value="custom">自定义消息</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="customMessage" class="form-label">自定义消息 (JSON格式)</label>
                                <input type="text" class="form-control" id="customMessage" placeholder='{"type":"test","data":"hello"}' value='{"type":"test","data":"hello"}'>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-grid">
                                    <button class="btn btn-primary" onclick="sendMessage()">发送消息</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 消息日志 -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5>消息日志</h5>
                        <button class="btn btn-sm btn-outline-secondary" onclick="clearLog()">清空日志</button>
                    </div>
                    <div class="card-body">
                        <div id="logContainer" class="log-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let ws = null;
        let messageCounter = 0;
        let connectionStartTime = null;
        
        function connect() {
            const userId = document.getElementById('userId').value;
            const serverUrl = document.getElementById('serverUrl').value;
            
            if (!userId) {
                addLog('请输入用户ID', 'error');
                return;
            }
            
            if (ws) {
                ws.close();
            }
            
            updateConnectionStatus('connecting', '连接中...');
            const url = `${serverUrl}?user_id=${userId}`;
            ws = new WebSocket(url);
            
            ws.onopen = function() {
                addLog('WebSocket连接已建立', 'success');
                updateConnectionStatus('connected', '已连接');
                connectionStartTime = new Date();
                document.getElementById('connectionTime').textContent = connectionStartTime.toLocaleTimeString();
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
                document.getElementById('pingBtn').disabled = false;
            };
            
            ws.onmessage = function(event) {
                messageCounter++;
                document.getElementById('messageCount').textContent = messageCounter;
                document.getElementById('lastMessage').textContent = new Date().toLocaleTimeString();
                
                try {
                    const data = JSON.parse(event.data);
                    addLog(`收到消息: ${JSON.stringify(data, null, 2)}`, 'info');
                } catch (e) {
                    addLog(`收到消息: ${event.data}`, 'info');
                }
            };
            
            ws.onclose = function() {
                addLog('WebSocket连接已关闭', 'warning');
                updateConnectionStatus('disconnected', '未连接');
                document.getElementById('connectBtn').disabled = false;
                document.getElementById('disconnectBtn').disabled = true;
                document.getElementById('pingBtn').disabled = true;
            };
            
            ws.onerror = function(error) {
                addLog(`WebSocket错误: ${error}`, 'error');
                updateConnectionStatus('disconnected', '连接错误');
            };
        }
        
        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }
        
        function ping() {
            sendMessageToServer({ type: 'ping' });
        }
        
        function sendMessage() {
            const messageType = document.getElementById('messageType').value;
            const customMessage = document.getElementById('customMessage').value;
            
            let message;
            if (messageType === 'custom') {
                try {
                    message = JSON.parse(customMessage);
                } catch (e) {
                    addLog('自定义消息格式错误，请使用JSON格式', 'error');
                    return;
                }
            } else {
                message = { type: messageType };
            }
            
            sendMessageToServer(message);
        }
        
        function sendMessageToServer(message) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(message));
                addLog(`发送消息: ${JSON.stringify(message)}`, 'info');
            } else {
                addLog('WebSocket未连接', 'error');
            }
        }
        
        function addLog(message, type = 'info') {
            const logContainer = document.getElementById('logContainer');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.innerHTML = `[${timestamp}] ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }
        
        function clearLog() {
            document.getElementById('logContainer').innerHTML = '';
            messageCounter = 0;
            document.getElementById('messageCount').textContent = '0';
        }
        
        function updateConnectionStatus(status, text) {
            const indicator = document.getElementById('statusIndicator');
            const statusText = document.getElementById('connectionStatus');
            
            indicator.className = `status-indicator status-${status}`;
            statusText.textContent = text;
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            addLog('WebSocket测试页面已加载', 'info');
            addLog('请点击"连接"按钮开始测试', 'info');
        });
    </script>
</body>
</html>
